/**
 * @ Author 何涛
 * @ Date 2016/02/23 10:33:16
 */

tyNamespace.TVMENU = "tvMenu";
var tableViewPro = tableViewPro || {};

if (typeof tableViewPro.ShowDirect == "undefined") {
    tableViewPro.ShowDirect = {};
    tableViewPro.ShowDirect.HORIZONTAL = 0;
    tableViewPro.ShowDirect.VERTICAL = 1;
}

if (typeof tableViewPro.MoveDirect == "undefined") {
    tableViewPro.MoveDirect = {};
    tableViewPro.MoveDirect.NONE = 0;
    tableViewPro.MoveDirect.LEFT = 1;
    tableViewPro.MoveDirect.RIGHT = 2;
    tableViewPro.MoveDirect.UP = 3;
    tableViewPro.MoveDirect.DOWN = 4;
}

if (typeof tableViewPro.FillStyle == "undefined") {
    tableViewPro.FillStyle = {};
    tableViewPro.FillStyle.TOP_DOWN = 0;
    tableViewPro.FillStyle.DOWN_TOP = 1;
}

tableViewPro.TableViewDelegate = cc.Class.extend({
    cellCallback: function (sender) {

    }
});

tableViewPro.TableViewDataSource = cc.Class.extend({
    getCellData: function (data) {

    }
});

tableViewPro.TableBar = function () {
    this.barInfo = null;
    this.barPosition = null;
};

tableViewPro.TableItem = function () {
    this.dataType = null;
    this.headInfo = null;
    this.pageInfo = null;
    this.pagePosition = null;
    this.cellInfo = null;
};

tableViewPro.TableView = cc.Node.extend({
    _dataSource: null,
    _delegate: null,
    _vOrdering: null,
    _showDirect: tableViewPro.ShowDirect.VERTICAL,
    _moveDirect: tableViewPro.MoveDirect.NONE,

    headHeight: null,
    viewSize: null,

    clippingNode: null,
    listener: null,

    data: null,
    tableBar: null,
    tableItems: [],
    currentItem: null,

    head: null,
    currentHeadItem: null,
    bar: null,
    barOffsetUp: null,
    barOffsetDown: null,
    currentPage: null,

    ctor: function (dataSource, size, headHeight) {
        this._super();

        this._dataSource = dataSource;
        this.headHeight = headHeight;
        this.viewSize = cc.size(size.width, size.height - headHeight);
        this.barOffsetUp = 0;
        this.barOffsetDown = 0;
        this.setContentSize(size);
        this.initWithSize();

        return true;
    },
    
    setsize:function(size){
    	this.viewSize =  cc.size(size.width, size.height);
    	this.initWithSize();
    },

    initWithSize: function () {
        var clipNode = new cc.ClippingNode(new cc.LayerColor(cc.color(0, 0, 0, 1), this.viewSize.width, this.viewSize.height));
        clipNode.attr({
            x: 0,
            y: 0,
            anchorX: 0,
            anchorY: 0
        });
        clipNode.setContentSize(this.viewSize);
        this.addChild(clipNode);
        this.clippingNode = clipNode;

        var self = this;
        var listener = cc.EventListener.create({
            event: cc.EventListener.TOUCH_ONE_BY_ONE,
            swallowTouches: true,
            onTouchBegan: self.onTouchBegan1,
            onTouchMoved: self.onTouchMoved1,
            onTouchEnded: self.onTouchEnded1
        });
        cc.eventManager.addListener(listener, this);
        this.listener = listener;
    },

    setTouchEnabled: function (e) {
        if (this.listener)
            cc.eventManager.removeListener(this.listener);
        this.listener = null;
        if (e) {
            var self = this;
            var listener = cc.EventListener.create({
                event: cc.EventListener.TOUCH_ONE_BY_ONE,
                swallowTouches: true,
                onTouchBegan: self.onTouchBegan1,
                onTouchMoved: self.onTouchMoved1,
                onTouchEnded: self.onTouchEnded1
            });
            cc.eventManager.addListener(listener, this);
            this.listener = listener;
        }
    },

    onTouchBegan1: function (touch, event) {
        var target = event.getCurrentTarget();

        if (target.tableItems.length == 0)
            return false;

        var size = target.viewSize;
        var locationInNode = target.clippingNode.convertToNodeSpace(touch.getLocation());
        var rect = cc.rect(0, 0, size.width, size.height);
        if (!cc.rectContainsPoint(rect, locationInNode)) {
            return false;
        }

        return true;
    },

    onTouchMoved1: function (touch, event) {
        var target;

        if (event instanceof cc.EventTouch) {
            target = event.getCurrentTarget();

            if (target.tableItems.length == 0)
                return false;

            var colCount = target.currentItem.pageInfo.colCount;
            var rowCount = Math.ceil(target.currentItem.cellInfo.cellCount / colCount);
            var cellHeight = target.currentItem.cellInfo.height;
            var pageSizeH = rowCount * cellHeight;
            var viewSizeH = target.viewSize.height;
            var barOffsetUp = target.barOffsetUp;
            var barOffsetDown = target.barOffsetDown;

            if (pageSizeH > viewSizeH) {
                var delta = touch.getDelta();

                var currentItem = target.currentItem;
                var tableBar = target.tableBar;
                //页面
                var currentPage = target.currentPage;
                var currentPagePosition = currentPage.getPosition();
                var minPageY = viewSizeH - pageSizeH;
                var maxPageY = 0;
                //滚动条
                var bar = target.bar;
                var barPosition = bar.getPosition();
                var minBarY = 0 + barOffsetDown;
                var maxBarY = viewSizeH - barOffsetUp - barOffsetDown - target.tableBar.barInfo.height;

                var scale = -minPageY / maxBarY;

                //cc.log("pageY:" + currentPagePosition.y + "---barY:" + barPosition.y);

                currentPage.setPositionY(currentPagePosition.y + delta.y);
                currentItem.pagePosition = cc.p(currentPagePosition.x, currentPagePosition.y + delta.y);

                bar.setPositionY(barPosition.y - delta.y / scale);
                tableBar.barPosition = cc.p(barPosition.x, barPosition.y - delta.y / scale);

                if (currentPagePosition.y + delta.y < minPageY) {
                    currentPage.setPositionY(minPageY);
                    currentItem.pagePosition = cc.p(currentPagePosition.x, currentPagePosition.y);

                    bar.setPositionY(maxBarY + barOffsetDown);
                    tableBar.barPosition = cc.p(barPosition.x, barPosition.y);
                }

                if (currentPagePosition.y + delta.y > maxPageY) {
                    currentPage.setPositionY(maxPageY);
                    currentItem.pagePosition = cc.p(currentPagePosition.x, currentPagePosition.y);

                    bar.setPositionY(minBarY);
                    tableBar.barPosition = cc.p(barPosition.x, barPosition.y);
                }
            }
        }
        else {
            target = event;

            if (target.tableItems.length == 0)
                return false;

            var colCount = target.currentItem.pageInfo.colCount;
            var rowCount = Math.ceil(target.currentItem.cellInfo.cellCount / colCount);
            var cellHeight = target.currentItem.cellInfo.height;
            var pageSizeH = rowCount * cellHeight;
            var viewSizeH = target.viewSize.height;
            var barOffsetUp = target.barOffsetUp;
            var barOffsetDown = target.barOffsetDown;

            if (pageSizeH > viewSizeH) {
                var delta = touch.getDelta();

                var currentItem = target.currentItem;
                var tableBar = target.tableBar;
                //页面
                var currentPage = target.currentPage;
                var currentPagePosition = currentPage.getPosition();
                var minPageY = viewSizeH - pageSizeH;
                var maxPageY = 0;
                //滚动条
                var bar = target.bar;
                var barPosition = bar.getPosition();
                var minBarY = 0 + barOffsetDown;
                var maxBarY = viewSizeH - barOffsetUp - barOffsetDown - target.tableBar.barInfo.height;

                var scale = -minPageY / maxBarY;

                currentPage.setPositionY(currentPagePosition.y + delta.y);
                currentItem.pagePosition = cc.p(currentPagePosition.x, currentPagePosition.y + delta.y);

                bar.setPositionY(barPosition.y - delta.y / scale);
                tableBar.barPosition = cc.p(barPosition.x, barPosition.y - delta.y / scale);

                if (currentPagePosition.y + delta.y < minPageY) {
                    currentPage.setPositionY(minPageY);
                    currentItem.pagePosition = cc.p(currentPagePosition.x, currentPagePosition.y);

                    bar.setPositionY(maxBarY + barOffsetDown);
                    tableBar.barPosition = cc.p(barPosition.x, barPosition.y);
                }

                if (currentPagePosition.y + delta.y > maxPageY) {
                    currentPage.setPositionY(maxPageY);
                    currentItem.pagePosition = cc.p(currentPagePosition.x, currentPagePosition.y);

                    bar.setPositionY(minBarY);
                    tableBar.barPosition = cc.p(barPosition.x, barPosition.y);
                }
            }
        }
    },

    onTouchEnded1: function (touch, event) {
        var target = event.getCurrentTarget();

        if (target.tableItems.length == 0)
            return false;
    },

    onExit: function () {
        this._super();

        //TODO 分页处理
        this.bar && this.bar.retain();
        this.currentPage && this.currentPage.retain();
    },

    addData: function (data) {
        this.data = data;

        var bar = new tableViewPro.TableBar();
        bar.barInfo = data.barInfo;
        bar.barPosition = cc.p(this.viewSize.width - data.barInfo.width / 2, this.viewSize.height - this.barOffsetUp - data.barInfo.height);
        this.tableBar = bar;

        for (var a = 0; a < data.sameItem.length; a++) {
            var item = new tableViewPro.TableItem();
            item.dataType = data.sameItem[a].dataType;
            item.headInfo = data.sameItem[a].headInfo;
            item.pageInfo = data.sameItem[a].pageInfo;
            item.cellInfo = data.sameItem[a].cellInfo;

            var colCount = data.sameItem[a].pageInfo.colCount;
            var rowCount = Math.ceil(data.sameItem[a].cellInfo.cellCount / colCount);
            var cellHeight = data.sameItem[a].cellInfo.height;
            var viewSizeH = this.viewSize.height;
            item.pagePosition = cc.p(0, viewSizeH - rowCount * cellHeight);

            this.tableItems.push(item);
        }
    },

    clearData: function () {
        this.tableBar = null;
        this.tableItems = [];
        this.currentItem = null;

        if (this.head)
            this.head.removeFromParent(true);
        if (this.bar)
            this.bar.removeFromParent(true);
        if (this.currentPage)
            this.currentPage.removeFromParent(true);

        this.head = null;
        this.currentHeadItem = null;
        this.bar = null;
        this.currentPage = null;
    },

    headSprite: function () {
        var headCount = this.tableItems.length;
        var headOffset = this.tableItems[0].headInfo.offset;
        var headWidth = this.tableItems[0].headInfo.width;
        var headHeight = this.headHeight / 2;

        for (var a = 0; a < headCount; a++) {
            var headBack = this.tableItems[a].headInfo.imageName;

            if (cc.isString(headBack)) {
                if (headBack != "") {
                    var headSprite = new cc.Sprite(headBack);
                    headSprite.attr({
                        x: headOffset + headSprite.getContentSize().width / 2 + headWidth * a,
                        y: this.viewSize.height + headHeight / 2
                    });
                    headSprite.setTag(a);
                    headSprite.setUserData(this.tableItems[a].dataType);
                    this.addChild(headSprite);
                }
                else {
                    var headSprite = new cc.LayerColor(cc.color(0, 0, 0, 255), headWidth, headHeight);
                    headSprite.attr({
                        x: headOffset + this.tableItems[0].headInfo.width * a,
                        y: this.viewSize.height
                    });
                    headSprite.setTag(a);
                    headSprite.setUserData(this.tableItems[a].dataType);
                    this.addChild(headSprite);
                }
            }

            if (cc.isArray(headBack)) {
                if (a % 2)
                    headBack = this.tableItems[a].headInfo.imageName[0];
                else
                    headBack = this.tableItems[a].headInfo.imageName[1];

                var headSprite = new cc.Sprite(headBack);
                headSprite.attr({
                    x: headOffset + headSprite.getContentSize().width / 2 + headWidth * a,
                    y: this.viewSize.height + headHeight / 2
                });
                headSprite.setTag(a);
                headSprite.setUserData(this.tableItems[a].dataType);
                this.addChild(headSprite);
            }
        }
    },

    headMenu: function () {
        //TODO
    },

    showHeads: function () {
        var headType = this.tableItems[0].headInfo.headType;
        switch (headType) {
            case 0://head sprite
                this.headSprite();
                break;

            case 1://head menu
                this.headMenu();
                break;
        }
    },

    headCallbackFunction: function (sender) {
        this.currentHeadItem = sender;
        //TODO 头部选中表现
        var dataType = sender.getUserData();
        this.showPageByDataType(dataType);
        this.adjustBar();
    },

    showBar: function () {
        var bar = new cc.LayerColor(cc.color(150, 101, 101, 255), this.tableBar.barInfo.width, this.tableBar.barInfo.height);
        bar.setPosition(this.tableBar.barPosition);
        this.addChild(bar);
        this.bar = bar;
    },

    //设置scrollbar 上下偏移node上下边框距离
    setBarOffset: function (offsetUp, offsetDown) {
        this.barOffsetUp = offsetUp;
        this.barOffsetDown = offsetDown;
    },

    showData: function (dataType) {
        if (this.tableItems.length == 0)
            return;

        if (this.headHeight != 0)
        	this.showHeads();
        	this.showBar();

        //TODO 自动打开第几页
        if (dataType == undefined)
            dataType = this.tableItems[0].dataType;
        this.showPageByDataType(dataType);

        var colCount = this.currentItem.pageInfo.colCount;
        var rowCount = Math.ceil(this.currentItem.cellInfo.cellCount / colCount);
        var cellHeight = this.currentItem.cellInfo.height;
        var pageHeight = rowCount * cellHeight;
        var viewSizeH = this.viewSize.height;

        if (pageHeight > viewSizeH)
            this.bar.setVisible(true);
        else
            this.bar.setVisible(false);
    },

    getSameDataTypeItem: function (dateType) {
        var sameData;
        for (var a = 0; a < this.tableItems.length; a++) {
            if (this.tableItems[a].dataType == dateType)
                sameData = this.tableItems[a];
        }
        return sameData;
    },

    cellSprite: function () {
        var colCount = this.currentItem.pageInfo.colCount;
        var rowCount = Math.ceil(this.currentItem.cellInfo.cellCount / colCount);
        var cellWidth = this.viewSize.width / colCount;
        var cellHeight = this.currentItem.cellInfo.height;

        for (var a = 0, c = 0; a < rowCount; a++) {
            for (var b = 0; b < colCount; b++) {
                if (c < this.currentItem.cellInfo.cellCount) {
                    var cellBack = this.currentItem.cellInfo.imageName;

                    if (cc.isString(cellBack)) {
                        if (cellBack != "") {
                            var cellItem = new cc.Sprite(cellBack);
                            cellItem.attr({
                                x: this.viewSize.width / colCount / 2 + this.viewSize.width / colCount * b,
                                y: cellHeight / 2 + cellHeight * (rowCount - a - 1)
                            });
                            cellItem.setTag(c);
                            this.currentPage.addChild(cellItem);
                        }
                        else {
                            var cellItem = new cc.LayerColor(cc.color(0, 0, 0, 1), cellWidth, cellHeight);
                            cellItem.attr({
                                x: this.viewSize.width / colCount * b,
                                y: cellHeight * (rowCount - a - 1)
                            });
                            cellItem.setTag(c);
                            this.currentPage.addChild(cellItem);
                        }
                    }

                    if (cc.isArray(cellBack)) {
                        if (c % 2)
                            cellBack = this.currentItem.cellInfo.imageName[0];
                        else
                            cellBack = this.currentItem.cellInfo.imageName[1];

                        var cellItem = new cc.Sprite(cellBack);
                        cellItem.attr({
                            x: this.viewSize.width / colCount / 2 + this.viewSize.width / colCount * b,
                            y: cellHeight / 2 + cellHeight * (rowCount - a - 1)
                        });
                        cellItem.setTag(c);
                        this.currentPage.addChild(cellItem);
                    }
                }
                c++;
            }
        }
    },

    cellMenu: function () {
        var colCount = this.currentItem.pageInfo.colCount;
        var rowCount = Math.ceil(this.currentItem.cellInfo.cellCount / colCount);
        var cellHeight = this.currentItem.cellInfo.height;

        var cellItems = [];
        for (var a = 0, c = 0; a < rowCount; a++) {
            for (var b = 0; b < colCount; b++) {
                if (c < this.currentItem.cellInfo.cellCount) {
                    var cellBack = this.currentItem.cellInfo.imageName;

                    if (cc.isString(cellBack)) {
                        if (cellBack != "") {
                            var item1 = new cc.Sprite(cellBack);
                            var item2 = new cc.Sprite(cellBack);
                            //var item2 = new xzgbNamespace.maskSprite(cellBack);
                            var cellItem = new cc.MenuItemSprite(item1, item2, this.cellCallbackFunction, this);
                            cellItem.attr({
                                x: this.viewSize.width / colCount / 2 + this.viewSize.width / colCount * b,
                                y: cellHeight / 2 + cellHeight * (rowCount - a - 1)
                            });
                        }
                        else {
                            //TODO 按钮没传imageName 生成大小的透明块
                            //var cellItem = new cc.LayerColor(cc.color(0, 0, 0, 1), cellWidth, cellHeight);
                            //cellItem.attr({
                            //    x: 0,
                            //    y: cellHeight * (rowCount - a - 1)
                            //});
                        }
                    }

                    if (cc.isArray(cellBack)) {
                        if (c % 2)
                            cellBack = this.currentItem.cellInfo.imageName[0];
                        else
                            cellBack = this.currentItem.cellInfo.imageName[1];

                        var item1 = new cc.Sprite(cellBack);
                        var item2 = new cc.Sprite(cellBack);
                        var cellItem = new cc.MenuItemSprite(item1, item2, this.cellCallbackFunction, this);
                        cellItem.attr({
                            x: this.viewSize.width / colCount / 2 + this.viewSize.width / colCount * b,
                            y: cellHeight / 2 + cellHeight * (rowCount - a - 1)
                        });
                    }

                    cellItems.push(cellItem);
                    cellItem.setTag(c);
                }
                c++;
            }
        }
        if (cellItems.length > 0) {
        	var cellMenu = new tableViewPro.Menu(cellItems);
//        	cellMenu.setMyParent(this);
        	cellMenu.setTouchListener(); 
            this.scheduleOnce(function () {
                cellMenu.setTouchArea(this.viewSize, this.clippingNode.getParent().convertToWorldSpace(this.clippingNode.getPosition()));
            }, 0.5);
            cellMenu.setPosition(0, 0);
            cellMenu.setName(tyNamespace.TVMENU);
            this.currentPage.addChild(cellMenu);
        }
    },

    cellCallbackFunction: function (sender) {
        this._delegate.cellCallback(sender);
    },

    showPageByDataType: function (dateType) {
        this.clippingNode.removeAllChildren();

        //TODO 分批加载
        var sameData = this.getSameDataTypeItem(dateType);
        this.currentItem = sameData;

        var colCount = this.currentItem.pageInfo.colCount;
        var rowCount = Math.ceil(this.currentItem.cellInfo.cellCount / colCount);
        var cellHeight = this.currentItem.cellInfo.height;
        var pageWidth = this.viewSize.width;
        var pageHeight = rowCount * cellHeight;

        var currentPage = new cc.LayerColor(cc.color(0, 0, 0, 1), pageWidth, pageHeight);
        currentPage.setPosition(this.currentItem.pagePosition);
        this.clippingNode.addChild(currentPage);
        this.currentPage = currentPage;

        var cellType = this.currentItem.cellInfo.cellType;
        switch (cellType) {
            case 0://cell sprite
                this.cellSprite();
                break;

            case 1://cell menu
                this.cellMenu();
                break;
        }
    },

    adjustBar: function () {
        //var colCount = this.currentItem.pageInfo.colCount;
        //var rowCount = Math.ceil(this.currentItem.cellInfo.cellCount / colCount);
        //var cellHeight = this.currentItem.cellInfo.height;
        //
        //if (this.bar.isVisible()) {
        //    this.bar.setPositionY((this.viewSize.height - this.tableBar.barInfo.height) * this.currentItem.pagePosition.y / (this.viewSize.height - rowCount * cellHeight));
        //}

        cc.log("this.tableBar.barPosition.y:" + this.tableBar.barPosition.y);
        this.bar.setPositionY(this.tableBar.barPosition.y);
    },

    setScrollPosition: function (index) {
        var offsetCount = Math.floor(this.viewSize.height / this.currentItem.cellInfo.height);
        var minIndex = offsetCount - 1;
        var maxIndex = this.currentItem.cellInfo.cellCount - 1 - offsetCount;
        var colCount = this.currentItem.pageInfo.colCount;
        var rowCount = Math.ceil(this.currentItem.cellInfo.cellCount / colCount);
        var cellHeight = this.currentItem.cellInfo.height;
        var pageSizeH = rowCount * cellHeight;
        var viewSizeH = this.viewSize.height;
        var perIndexTime = 0.01;
        var currentScrolled;

        if (index <= minIndex)
            currentScrolled = this.currentItem.pagePosition.y - (viewSizeH - pageSizeH);
        else if (index >= maxIndex)
            currentScrolled = this.currentItem.pagePosition.y;
        else
            currentScrolled = this.currentItem.pagePosition.y - (viewSizeH - (index + 1) * cellHeight);

        var scrolledIndex = Math.abs(currentScrolled) / cellHeight;

        var self = this;
        this.currentPage.runAction(cc.sequence(cc.moveBy(scrolledIndex * perIndexTime, 0, -currentScrolled), cc.callFunc(function () {
            self.currentItem.pagePosition = cc.p(self.currentPage.getPosition().x, self.currentPage.getPosition().y);
        })));

        //bar
        var barOffsetUp = this.barOffsetUp;
        var barOffsetDown = this.barOffsetDown;
        var minPageY = viewSizeH - pageSizeH;
        var maxBarY = viewSizeH - barOffsetUp - barOffsetDown - this.tableBar.barInfo.height;

        var scale = -minPageY / maxBarY;

        var self = this;
        this.bar.runAction(cc.sequence(cc.moveBy(scrolledIndex * perIndexTime, 0, currentScrolled / scale), cc.callFunc(function () {
            self.tableBar.barPosition = cc.p(self.bar.getPosition().x, self.bar.getPosition().y);
        })));
    },

    /**
     * data source
     */
    getDataSource: function () {
        return this._dataSource;
    },
    setDataSource: function (source) {
        this._dataSource = source;
    },

    /**
     * delegate
     */
    getDelegate: function () {
        return this._delegate;
    },

    setDelegate: function (delegate) {
        this._delegate = delegate;
    },

    /**
     * determines how cell is ordered and filled in the view.
     */
    getVerticalFillOrder: function () {
        return this._vOrdering;
    },

    setVerticalFillOrder: function (fillOrder) {
        if (this._vOrdering != fillOrder) {
            this._vOrdering = fillOrder;
            if (this._cellsUsed.count() > 0) {
                this.reloadData();
            }
        }
    },

    /**
     * show direct
     */
    getShowDirect: function () {
        return this._showDirect;
    },

    setShowDirect: function (direct) {
        this._showDirect = direct;
    },

    /**
     * move direct
     */
    getMoveDirect: function () {
        return this._moveDirect;
    },

    setMoveDirect: function (direct) {
        this._moveDirect = direct;
    }
    
});

var _p = tableViewPro.TableView.prototype;

/** @expose */
_p.dataSource;
cc.defineGetterSetter(_p, "dataSource", _p.getDataSource, _p.setDataSource);
/** @expose */
_p.delegate;
cc.defineGetterSetter(_p, "delegate", _p.getDelegate, _p.setDelegate);
/** @expose */
_p.showDirect;
cc.defineGetterSetter(_p, "showDirect", _p.getShowDirect, _p.setShowDirect);
/** @expose */
_p.showDirect;
cc.defineGetterSetter(_p, "moveDirect", _p.getMoveDirect, _p.setMoveDirect);
/** @expose */
_p.verticalFillOrder;
cc.defineGetterSetter(_p, "verticalFillOrder", _p.getVerticalFillOrder, _p.setVerticalFillOrder);

_p = null;